package com.oh.iris.server.security;

import com.oh.iris.dao.SysUserDao;
import com.oh.iris.entity.SysUserEntity;
import com.oh.iris.entity.UserDetail;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * 账号登录 UserDetailsService
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserDao sysUserDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity userEntity = sysUserDao.getByUsername(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        // 转换成UserDetail对象
        UserDetail userDetail = new UserDetail();
        userDetail.setUsername(userEntity.getUserName());
        userDetail.setId(userEntity.getId());
        userDetail.setEmail(userEntity.getEmail());
        userDetail.setPassword(userEntity.getPassword());
        userDetail.setMobile(userEntity.getMobile());

        Set<String> permsSet = new HashSet<>();
        permsSet.add("*"); // 权限，不能为空
        userDetail.setAuthoritySet(permsSet);
        return userDetail;
    }

}
